package com.lz.ionicbase.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.lz.ionicbase.R;
import com.lz.ionicbase.SuperApp;
import com.lz.ionicbase.engine.LoginHelper;
import com.lz.ionicbase.ui.activity.action.IloginView;
import com.lz.ionicbase.utils.BaseUtil;
import com.lz.ionicbase.utils.Constant;
import com.lz.ionicbase.utils.ControlLoading;
import com.lz.ionicbase.utils.EditTextUtils;
import com.lz.ionicbase.utils.SpUtils;
import com.lz.ionicbase.utils.ToastUtils;

import java.util.HashMap;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

/**
 * Created by lenovo on 2017/2/10.
 */

public class LoginActivity extends BaseActivity implements IloginView {

    @InjectView(R.id.login_img)
    ImageView loginImg;
    @InjectView(R.id.username_et)
    EditText usernameEt;
    @InjectView(R.id.password_et)
    EditText passwordEt;
    @InjectView(R.id.cb_mima)
    CheckBox cbMima;
    @InjectView(R.id.cb_auto)
    CheckBox cbAuto;
    @InjectView(R.id.login_bottom_tv)
    TextView loginBottomTv;
    @InjectView(R.id.login_forget)
    TextView loginForget;
    private String username;
    private String userpsw;
    private TelephonyManager telephonyManager;
    private SpUtils sp = new SpUtils();
    private String deviceId;
    private static final int RECODE_SETSERVER = 100;

    @Override
    protected int getActivityLayout() {
        return R.layout.activity_login;
    }

    /**
     * 其中有实现自动登陆和记住密码
     */
    @Override
    protected void initView() {
        ButterKnife.inject(this);
        //EditText初始化
        username = usernameEt.getText().toString();
        userpsw = passwordEt.getText().toString();
        EditTextUtils.stringFilter(this, usernameEt);
        EditTextUtils.stringFilter(this, passwordEt);
        //登录按键初始化为可用
        loginImg.setEnabled(true);

        if (sp.getBoolean(this, Constant.ISCHECK, false)) {
            cbMima.setChecked(true);
            usernameEt.setText(sp.getString(this, Constant.ACCOUNT, ""));
            passwordEt.setText(sp.getString(this, Constant.MIMA, ""));
            usernameEt.setSelection(usernameEt.length());
            passwordEt.setSelection(passwordEt.length());
            if (sp.getBoolean(this, Constant.ISAUTO, false)) {
                //设置默认是自动登录状态
                cbAuto.setChecked(true);
                //跳转界面
                loginInto();
            }
        }
    }

    /**
     * 监听自动登录和记住密码
     */
    @Override
    protected void initListener() {
        cbMima.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (cbMima.isChecked()) {
                    sp.saveBoolean(LoginActivity.this, Constant.ISCHECK, true);
                } else {
                    sp.saveBoolean(LoginActivity.this, Constant.ISCHECK, false);
                }
            }
        });
        cbAuto.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (cbAuto.isChecked()) {
                    sp.saveBoolean(LoginActivity.this, Constant.ISAUTO, true);
                } else {
                    sp.saveBoolean(LoginActivity.this, Constant.ISAUTO, false);
                }
            }
        });
    }

    /**
     * 给登录请求传参
     *
     * @return
     */
    @Override
    public Map<String, String> getLoginParam() {
        username = usernameEt.getText().toString();
        userpsw = passwordEt.getText().toString();
        //base64
        String username1 = BaseUtil.getBase64(username);
        String userpsw1 = BaseUtil.getBase64(userpsw);
        //uid
        telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        deviceId = telephonyManager.getDeviceId();
        // deviceId = Android.os.Build.SERIAL;
        Log.i("uid", deviceId);
        sp.saveString(LoginActivity.this, Constant.DEVICEID, deviceId);

        String spLan  = SpUtils.getString(getApplicationContext(), SpUtils.KEY_LANGUAGE,"简体中文");
        String language = (String) SuperApp.lanMap.get(spLan)[0];
        //参数
        Map<String, String> parmas = new HashMap();
        parmas.put("uid", deviceId);
        parmas.put("loginName", username1);
        parmas.put("password", userpsw1);
        parmas.put("language", language);
        return parmas;
    }

    /**
     * 拼接登录url
     *
     * @return
     */
    @Override
    public String getUrl() {
        String ip = sp.getString(this, Constant.SERVERIP, "");
        String port = sp.getString(this, Constant.PORT, "");
        String loginMsgurl = Constant.URLLOG + ip + ":" + port + "/project/";
        String netUrl = Constant.URLLOG + ip + ":" + port;
        sp.saveString(this, Constant.MAIN_URL, loginMsgurl);
        sp.saveString(this, Constant.NET_URL, netUrl);
        String url = netUrl + Constant.LOGIN;
        return url;
    }

    @OnClick({R.id.login_img, R.id.login_bottom_tv, R.id.login_forget})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.login_img:
                startActivity(new Intent(this, MainActivity.class));
//                loginData();
                break;
            case R.id.login_bottom_tv:
                Intent intent = new Intent(this, SetServerActivity.class);
                startActivityForResult(intent, RECODE_SETSERVER);
                break;
            case R.id.login_forget:
                Intent intent2 = new Intent(this, PsdInputPhoneActivity.class);
                startActivity(intent2);
                break;
        }
    }

    private void loginData() {
        loginInto();
    }

    /**
     * 登录进主页面
     */
    private void loginInto() {
//        boolean setServer = sp.getBoolean(this, Constant.SETSERVER, false);
        String baseUrl = sp.getString(this, SpUtils.KEY_BASE_URL, "");

        if (!TextUtils.isEmpty(baseUrl)) {
            if (BaseUtil.isValidContext(this)) {
                ControlLoading.showDialog(this, "正在登录....");
            }
            LoginHelper loginHelper = new LoginHelper(this);
            loginHelper.login();
        } else {
            Intent intent = new Intent(this, SetServerActivity.class);
            startActivityForResult(intent, RECODE_SETSERVER);
        }
    }

    /**
     * 请求网络成功后在Activity中的一些操作
     * @param
     * @param code
     */
    @Override
    public void toMainActivity(String token, String code,String myusername) {
        //保存帐号，密码，token
        sp.saveString(this, Constant.ACCOUNT, username);
        sp.saveString(this, Constant.MIMA, userpsw);
        sp.saveString(this, Constant.TOKEN, token);
        sp.saveString(this,Constant.USERNAME,myusername);
        Toast.makeText(LoginActivity.this, "成功", Toast.LENGTH_SHORT).show();
        //判断并跳转主页面
        if (TextUtils.equals(code, "100") || TextUtils.equals(code, "200")) {
            //登陆完成设置cookie
            SuperApp.setAppCookie();
            //设置当前WIFI ssid
            ((SuperApp)getApplication()).setCurrWifiIP();

            Intent intent = new Intent(this, MainActivity.class);
            startActivity(intent);
            finish();
        }
    }

    /**
     * 网络请求错误
     */
    @Override
    public void ShowError() {
        ControlLoading.closeDialog();
        //登录按钮设置有效
        loginImg.setEnabled(true);
//        Toast.makeText(LoginActivity.this, "请检查服务器设置", Toast.LENGTH_SHORT).show();
//        Intent intent = new Intent(this, SetServerActivity.class);
//        startActivityForResult(intent, RECODE_SETSERVER);
    }

    /**
     * 帐号密码为空
     */
    @Override
    public void ShowEmpty() {
        ControlLoading.closeDialog();
        Toast.makeText(LoginActivity.this, "请填写帐号和密码", Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ControlLoading.closeDialog();

    }

    public void ShowOtherError(String desc) {
        ControlLoading.closeDialog();
        loginImg.setEnabled(true);
        if (desc.equals("密码无效")){
            passwordEt.setTextColor(getResources().getColor(R.color.error));
        }else if (desc.equals("用户名无效")){
            usernameEt.setTextColor(getResources().getColor(R.color.error));
        }
        ToastUtils.showToast(LoginActivity.this,desc,1);
    }
}
